package ck.android.englishschool.thread;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.util.Log;
import ck.android.englishschool.AppStatus;
import ck.android.englishschool.util.Const;
import ck.android.englishschool.util.JSONParser;
import ck.android.englishschool.util.ParameterUtil;
import ck.android.englishschool.vo.WordDetailVO;

public class WordDatailThread extends BaseThread{
	private WordDetailVO wordDetailVO;
	public WordDatailThread(Context context
			, ThreadCallBack callBack, WordDetailVO wordDetailVO){
		this.context = context;
		this.callBack = callBack;
		this.appStatus = (AppStatus) context.getApplicationContext();
		this.wordDetailVO = wordDetailVO; 
	}
	
	@Override
	public void run() {
		// 통신불통상태이면
		if(!appStatus.utilm.isNetworkConnected(context)) {
			callBack.threadCompleted(false, null, "통신 에러");
			return;
		}
		JSONParser jParser = new JSONParser();
		
		url = Const.MAIN_URL;
		post = ParameterUtil.getWordDetailParams(wordDetailVO);
		
		JSONObject json = jParser.getJSONFromUrl(url, post);
		Log.i("url","url = " + url + post);
		Log.i("json","json = " + json);
		if(json == null) {
			callBack.threadError("데이터가 없습니다.");
			return;
		}
		try {
			int result = json.getInt(Const.RESULT);
			String message = json.getString(Const.MESSAGE);
			
			ArrayList<WordDetailVO> arrWordDetail = null;
			if(result == 0){
				callBack.threadError(message);
			}
			else{
				JSONArray jArray = json.getJSONArray(Const.DATA);
				arrWordDetail = new ArrayList<WordDetailVO>();
				WordDetailVO vo = null;
				for(int i=0; i<jArray.length(); i++){
					JSONObject obj = jArray.getJSONObject(i);
					vo = new WordDetailVO();
					vo.setDetailSeq(appStatus.utilm.getStringJSONObject(obj, WordDetailVO.DETAIL_SEQ));
					vo.setTitle(appStatus.utilm.getStringJSONObject(obj, WordDetailVO.TITLE));
					vo.setWord(appStatus.utilm.getStringJSONObject(obj, WordDetailVO.WORD));
					vo.setkWord(appStatus.utilm.getStringJSONObject(obj, WordDetailVO.K_WORD));
					vo.setWordVal(appStatus.utilm.getStringJSONObject(obj, WordDetailVO.WORD_VAL));
					vo.setRegDate(appStatus.utilm.getStringJSONObject(obj, WordDetailVO.REG_DATE));
					vo.setUpDate(appStatus.utilm.getStringJSONObject(obj, WordDetailVO.UP_DATE));
					vo.setIdentyfy(appStatus.utilm.getStringJSONObject(obj, WordDetailVO.IDENTYFY));
					vo.setUserLevel(appStatus.utilm.getStringJSONObject(obj, WordDetailVO.USER_LEVEL));
					arrWordDetail.add(vo);
				}
				appStatus.setArrWordDetail(arrWordDetail);
				callBack.threadCompleted(true, true, "성공");
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		
		
	}
	
}
